package com.example.UI;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.UI.database.MySQLDataHelper;
import com.example.UI.entity.User;
import com.example.ui.R;


public class AddStudentActivity extends AppCompatActivity {

    private EditText aUsername;
    private EditText aPassword;
    private EditText aName;
    private EditText aId;
    private Spinner aClass;
    private Button addStudentButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_student);
        aUsername = findViewById(R.id.a_et_username);
        aPassword = findViewById(R.id.a_et_psw);
        aName = findViewById(R.id.a_et_name);
        aId = findViewById(R.id.a_et_id);
        aClass = findViewById(R.id.a_spi_class);
        addStudentButton = findViewById(R.id.addStudentButton);

        addStudentButton.setOnClickListener(new View.OnClickListener() {
            // AddStudentActivity.java 中的 onClick 方法内
            @Override
            public void onClick(View v) {
                String username = aUsername.getText().toString();
                String password = aPassword.getText().toString();
                String name = aName.getText().toString();
                String id = aId.getText().toString();
                String selectedClass = aClass.getSelectedItem().toString();

                if (username.isEmpty() || password.isEmpty() || name.isEmpty() || id.isEmpty() || selectedClass.isEmpty()) {
                    Toast.makeText(AddStudentActivity.this, "请输入完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    // 创建 User 对象
                    User newUser = new User(id, name, selectedClass, username, password);

                    // 获取 MySQLDataHelper 实例
                    MySQLDataHelper dbHelper = new MySQLDataHelper(AddStudentActivity.this);

                    // 尝试将 User 对象添加到数据库
                    long insertId = dbHelper.register(newUser);

                    // 检查是否添加成功
                    if (insertId != -1) {
                        // 添加成功
                        Toast.makeText(AddStudentActivity.this, "学生信息已添加：" + name + ", " + selectedClass, Toast.LENGTH_SHORT).show();
                        // 清空输入框和Spinner
                        aUsername.setText("");
                        aPassword.setText("");
                        aName.setText("");
                        aId.setText("");
                        aClass.setSelection(0);
                    } else {
                        // 添加失败
                        Toast.makeText(AddStudentActivity.this, "添加学生信息失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}